/**
******************************************************************************
* @file    main.c 
* @author  jobs
* @version v0.00
* @date    2021-09-19
* @brief   
* @note    
*
******************************************************************************
*/

#include <stdint.h>
#include "chip.h"

#include "bsp.h"
#include "led.h"

uint32_t timeline_ms = 0;
uint32_t jtag_delay = 0;
uint32_t next_triggler_value = 0;

typedef enum
{
	TIMER_MATCH_CHN_0,
	TIMER_MATCH_CHN_1,
	TIMER_MATCH_CHN_2,
	TIMER_MATCH_CHN_3
} TIMER_MATCH_CHN_T;

void main(void)
{
	bsp_init();

	timeline_ms = 0;
	SysTick_Config(4000);

	while (1)
	{
		__WFI();
		if (jtag_delay > 4000)
		{
			break;
		}
	}

	led_init();
	led_disp_buf[0] = 0xFF;
	led_disp_buf[1] = 0xFF;
	led_disp_buf[2] = 0xFF;
	led_disp_buf[3] = 0xFF;
	led_disp_buf[4] = 0xFF;

	/* configure 16-bit Timer CT16B 
       - free running 
       - set 1 second of interval for generating internal event to toggle LED
       PCLK = 2000000hz (system clock); interval time = 1s = (MR value) * (PR value + 1) * 1/PCLK
    */
	Chip_TIMER16_0_Init();																					 // initialize 16-bit timer
	Chip_TIMER_Reset(LPC_TIMER16_0);																 // reset 16-bit timer (PC&TC) for a new count
	Chip_TIMER_PrescaleSet(LPC_TIMER16_0, 49);											 // set the maximum value for Prescale Counter
	Chip_TIMER_SetMatch(LPC_TIMER16_0, TIMER_MATCH_CHN_0, 160);			 // set time counter match value
	Chip_TIMER_MatchEnableInt(LPC_TIMER16_0, TIMER_MATCH_CHN_0);		 // enable interrupt flag on match of channel 0
																																	 //    Chip_TIMER_StopOnMatchEnable(LPC_TIMER16_0, TIMER_MATCH_CHN_0);   // enable stop flag on match of channel 0
	Chip_TIMER_ResetOnMatchEnable(LPC_TIMER16_0, TIMER_MATCH_CHN_0); // enable reset flag on match of channel 0
	NVIC_EnableIRQ(CT16B0_IRQn);

	/* enable the timer to start counting */
	Chip_TIMER_Enable(LPC_TIMER16_0);

	while (1)
	{
		__WFI();
	}
}

void SysTick_Handler(void)
{
	jtag_delay++;
	timeline_ms++;
}

void CT16B0_IRQHandler(void)
{
	/* Get Timer Interrupt Status */
	if (Chip_TIMER_MatchPending(LPC_TIMER16_0, 0))
	{
		/* Clean-up Timer Interrupt Status */
		Chip_TIMER_ClearMatch(LPC_TIMER16_0, 0);
		/* set the flag for interval event  */
		led_display();
	}
}

/******************************** END OF FILE *********************************/
